package com.ruoyi.web.controller.inventory;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.system.domain.InvInventoryCheck;
import com.ruoyi.system.domain.InvInventoryWorkOrder;
import com.ruoyi.system.domain.Warehouse;
import com.ruoyi.system.dto.ExecuteOrUpdateDTO;
import com.ruoyi.system.dto.WorkOrderDTO;
import com.ruoyi.system.service.IWarehouseService;
import com.ruoyi.system.service.InvInventoryCheckService;
import com.ruoyi.system.service.InvInventoryWorkOrderService;
import com.ruoyi.system.util.AbdulEmptyUtils;
import com.ruoyi.system.util.BaseResponse;
import com.ruoyi.system.util.StoreIdUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/work-order")
@Api(tags = "门店库存盘点工单管理")
public class InvInventoryWorkOrderController {

    @Autowired
    private InvInventoryWorkOrderService workOrderService;

    @Autowired
    private StoreIdUtils storeIdUtils;

    @Autowired
    private InvInventoryCheckService checkService;

    @Autowired
    private IWarehouseService warehouseService;

    @PostMapping("/page")
    @ApiOperation("分页查询工单列表")
    public BaseResponse<Page<InvInventoryWorkOrder>> page(@RequestBody WorkOrderDTO workOrderDTO) {
        LambdaQueryWrapper<InvInventoryWorkOrder> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(!AbdulEmptyUtils.isEmpty(workOrderDTO.getInventoryNumber()), InvInventoryWorkOrder::getInventoryNumber, workOrderDTO.getInventoryNumber());
        wrapper.eq(!AbdulEmptyUtils.isEmpty(workOrderDTO.getWarehouseId()), InvInventoryWorkOrder::getWarehouseId, workOrderDTO.getWarehouseId());
        wrapper.eq(InvInventoryWorkOrder::getStoreId, storeIdUtils.getStoreId());
        if (!AbdulEmptyUtils.isEmpty(workOrderDTO.getCreateTimeStart()) && !AbdulEmptyUtils.isEmpty(workOrderDTO.getCreateTimeEnd())) {
            wrapper.between(InvInventoryWorkOrder::getCreateTime, workOrderDTO.getCreateTimeStart(), workOrderDTO.getCreateTimeEnd());
        }
        if (!AbdulEmptyUtils.isEmpty(workOrderDTO.getStocktakingTimeStart()) && !AbdulEmptyUtils.isEmpty(workOrderDTO.getStocktakingTimeEnd())) {
            wrapper.between(InvInventoryWorkOrder::getStocktakingTime, workOrderDTO.getStocktakingTimeStart(), workOrderDTO.getStocktakingTimeEnd());
        }
        wrapper.orderByDesc(InvInventoryWorkOrder::getUpdateTime);
        Page<InvInventoryWorkOrder> page = workOrderService.page(new Page<>(workOrderDTO.getPageNum(), workOrderDTO.getPageSize()), wrapper);
        if (!AbdulEmptyUtils.isEmpty(page.getRecords())) {
            Set<Long> collect = page.getRecords().stream().map(InvInventoryWorkOrder::getWarehouseId).collect(Collectors.toSet());
            LambdaQueryWrapper<Warehouse> query = Wrappers.lambdaQuery();
            query.in(Warehouse::getId, collect);
            List<Warehouse> warehouseList = warehouseService.list(query);
            Map<Long, String> map = warehouseList.stream().collect(Collectors.toMap(Warehouse::getId, Warehouse::getWarehouseName));
            for (InvInventoryWorkOrder record : page.getRecords()) {
                Long warehouseId = record.getWarehouseId();
                if (!AbdulEmptyUtils.isEmpty(map)) {
                    record.setWarehouseIdDesc(map.get(warehouseId));
                }
            }
        }
        return BaseResponse.success(page);
    }

    @PostMapping("/save")
    @ApiOperation("新增盘点工单")
    public BaseResponse<Boolean> save(@RequestBody InvInventoryWorkOrder order) {
        return BaseResponse.success(workOrderService.add(order));
    }

    /**
     * 执行工单任务
     * type :1 修改盘点工单
     * type :2 执行盘点单
     */
    @PostMapping("/executeOrUpdate")
    public BaseResponse<Boolean> executeOrUpdate(@RequestBody ExecuteOrUpdateDTO executeOrUpdateDTO) {
        return BaseResponse.success(workOrderService.executeOrUpdate(executeOrUpdateDTO));
    }

    /**
     * 工单详情
     */
    @GetMapping("/detail")
    @ApiOperation("盘点工单详情")
    public BaseResponse<ExecuteOrUpdateDTO> detail(Long id) {
        if (AbdulEmptyUtils.isEmpty(id)) {
            return BaseResponse.error("请选择盘点工单");
        }
        LambdaQueryWrapper<InvInventoryWorkOrder> lqw = Wrappers.lambdaQuery();
        lqw.eq(InvInventoryWorkOrder::getId, id);
        lqw.eq(InvInventoryWorkOrder::getIsDelete, 0);
        InvInventoryWorkOrder workOrder = workOrderService.getById(id);
        if (AbdulEmptyUtils.isEmpty(workOrder)) {
            return BaseResponse.error("此盘点工单不存在");
        }
        ExecuteOrUpdateDTO executeOrUpdateDTO = new ExecuteOrUpdateDTO();
        BeanUtils.copyProperties(workOrder, executeOrUpdateDTO);
        LambdaQueryWrapper<InvInventoryCheck> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(InvInventoryCheck::getWorkOrderId, id);
        wrapper.eq(InvInventoryCheck::getStoreId, storeIdUtils.getStoreId());
        List<InvInventoryCheck> list = checkService.list(wrapper);
        executeOrUpdateDTO.setCheckList(list);
        return BaseResponse.success(executeOrUpdateDTO);
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除盘点工单")
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<Boolean> delete(@PathVariable Long id) {
        if (AbdulEmptyUtils.isEmpty(id)) {
            return BaseResponse.error("参数ID不能为空");
        }
        InvInventoryWorkOrder byId = workOrderService.getById(id);
        if (AbdulEmptyUtils.isEmpty(byId)) {
            return BaseResponse.error("此盘点工单不存在");
        }
        LambdaQueryWrapper<InvInventoryCheck> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(InvInventoryCheck::getWorkOrderId, id);
        List<InvInventoryCheck> list = checkService.list(wrapper);
        if (!AbdulEmptyUtils.isEmpty(list)) {
            checkService.removeBatchByIds(list);
        }
        return BaseResponse.success(workOrderService.removeById(id));
    }
}
